package com.example.zhidingyiview.zhidingyiview;

import android.content.Context;
import android.graphics.drawable.ColorDrawable;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;

import com.example.zhidingyiview.R;

import java.util.ArrayList;

public class Spinner extends RelativeLayout implements View.OnClickListener {
    private EditText mEt;
    private ImageView mIv;
    private PopupWindow mPopupWindow;
    private ArrayList<String> mList;
    //两个参数的构造是必须的
    //为什么???AttributeSet attrs xml里面写的属性最终都会封装到这个对象中
    public Spinner(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        initData();
        View inflate = LayoutInflater.from(context).inflate(R.layout.spinner, null);
        mEt = inflate.findViewById(R.id.et);
        mIv = inflate.findViewById(R.id.iv);
        mIv.setOnClickListener(this);
        addView(inflate);
    }

    private void initData() {
        mList = new ArrayList<>();
        for (int i = 0; i < 30; i++) {
            mList.add("秋衣:"+i);
        }
    }
    public Spinner(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv:
                pop();
                break;
        }
    }
    private void pop() {
        if (mPopupWindow == null){
            ListView listView = new ListView(getContext());
            ArrayAdapter<String> adapter = new ArrayAdapter<String>(getContext(),
                    android.R.layout.simple_list_item_1,mList);
            listView.setAdapter(adapter);
            //三要素:view,宽,高
            mPopupWindow = new PopupWindow(listView, mEt.getWidth(), 500);
            //点击外部消失
            //低版本需要加背景,高版本不需要
            mPopupWindow.setBackgroundDrawable(new ColorDrawable());
            mPopupWindow.setOutsideTouchable(true);

            listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                    mPopupWindow.dismiss();
                    String text = mList.get(position);
                    mEt.setText(text);
                    //光标定位到最后
                    mEt.setSelection(text.length());
                }
            });
        }

        //在给定的控件下方显示,可以添加偏移量
        mPopupWindow.showAsDropDown(mEt);
        //在给定控件的父容器的某个位置显示
        //popupWindow.showAtLocation();
    }
}
